package so.shanku.essential.fragment;

import android.os.Bundle;

import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.*;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import so.shanku.essential.R;
import so.shanku.essential.activity.MainActivity;
import so.shanku.essential.activity.ShopThemeActivity;
import so.shanku.essential.adapter.BrandSearchAdapter;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.Utils;
import so.shanku.essential.utils.searchUtils.CharacterParser;
import so.shanku.essential.utils.searchUtils.PinyinComparator;
import so.shanku.essential.utils.searchUtils.SideBar;
import so.shanku.essential.utils.searchUtils.SortModel;


import java.util.*;

/**
 * Created by Administrator on 2015/9/7.
 */
public class BrandSearchFragment extends BaseFragment {
	/**
	 * 搜索框的隐藏与显示
	 */
	@ViewInject(R.id.linearlayout_search)
	private LinearLayout linearlayout_search;
	/**
	 * 搜索商品
	 */
	@ViewInject(R.id.search_ed)
	private EditText search_ed;
	@ViewInject(R.id.do_search_iv)
	private ImageView do_search_iv;
	/**
	 * 搜索取消
	 */
	@ViewInject(R.id.tv_search_cancel)
	private TextView tv_search_cancel;
	/**
	 * 弹出的字母
	 */
	@ViewInject(R.id.brand_select_new_dialog)
	private TextView dialog;
	/**
	 * 品牌搜索引擎
	 */
	@ViewInject(R.id.brand_select_new_sidrbar)
	private SideBar sideBar;
	@ViewInject(R.id.xlistview_brand_search)
	private ListView xlistview_brand_search;
	private BrandSearchAdapter searchBrandAdapter;
	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;
	private List<SortModel> SourceDateList;
	private String searchWord = "";
	private List<JsonMap<String, Object>> dataSearch;//搜索数据

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_brand_search, container, false);
		initCompont(view);
		linearlayout_search.setVisibility(View.VISIBLE);
		search_ed.setHint(R.string.search_brand);
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();

		pinyinComparator = new PinyinComparator();
		getData_Search();
		search_ed.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {

					searchWord = search_ed.getText().toString();
					getData_Search();
					return true;
				}
				return false;
			}
		});
		return view;
	}

	/**
	 * 搜索
	 *
	 * @param view
	 */
	@OnClick(R.id.do_search_iv)
	public void do_search_iv_click(View view){
		searchWord = search_ed.getText().toString();
		getData_Search();
	}

	@OnClick(R.id.tv_search_cancel)
	public void cancel_search_tv_click(View view) {
		((MainActivity) activity).setSelectItem(3);
	}

	public void initCompont(View view) {
		ViewUtils.inject(this, view);
	}

	private void initViews() {
		sideBar.setTextView(dialog);

		//设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				//该字母首次出现的位置
				int position = searchBrandAdapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					xlistview_brand_search.setSelection(position);
				}

			}
		});

		xlistview_brand_search.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
			                        int position, long id) {
				//这里要利用adapter.getItem(position)来获取当前position所对应的对象
				Bundle bundle = new Bundle();
				bundle.putString(Constant.VENDOR_ID, SourceDateList.get(position).getId());
				bundle.putString(Constant.VENDOR_NAME, SourceDateList.get(position).getName());
				activity.jumpTo(ShopThemeActivity.class, bundle, false);
			}
		});

		// 根据a-z进行排序源数据
		Collections.sort(SourceDateList, pinyinComparator);
		searchBrandAdapter = new BrandSearchAdapter(getActivity(), SourceDateList, callback2);
		xlistview_brand_search.setAdapter(searchBrandAdapter);

//        //根据输入框输入值的改变来过滤搜索
//        et_searchbrand.addTextChangedListener(new TextWatcher() {
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
//                filterData(s.toString());
//            }
//
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count,
//                                          int after) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//            }
//        });
	}


	/**
	 * 为ListView填充数据
	 *
	 * @param date
	 * @return
	 */
	private List<SortModel> filledData(List<JsonMap<String, Object>> date) {
		List<SortModel> mSortList = new ArrayList<SortModel>();
		for (int i = 0; i < date.size(); i++) {
			SortModel sortModel = new SortModel();
			sortModel.setId(date.get(i).getStringNoNull("id"));
			sortModel.setName(date.get(i).getStringNoNull("ShopName"));
			sortModel.setIv_log_url(date.get(i).getStringNoNull("brandLogo"));
			sortModel.setTv_msg(date.get(i).getStringNoNull("BusinessCategory"));
			sortModel.setFocus(date.get(i).getBoolean("isFocusOn", false));
			//汉字转换成拼音
			String pinyin = characterParser.getSelling(date.get(i).getStringNoNull("ShopName"));
			try {
				String sortString = pinyin.substring(0, 1).toUpperCase();

				// 正则表达式，判断首字母是否是英文字母
				if (sortString.matches("[A-Z]")) {
					sortModel.setSortLetters(sortString.toUpperCase());
				} else {
					sortModel.setSortLetters("#");
				}

				mSortList.add(sortModel);
			} catch (StringIndexOutOfBoundsException e) {
				e.printStackTrace();
			}

		}
		return mSortList;

	}
//
//    /**
//     * 根据输入框中的值来过滤数据并更新ListView
//     *
//     * @param filterStr
//     */
//    private void filterData(String filterStr) {
//        List<SortModel> filterDateList = new ArrayList<SortModel>();
//
//        if (TextUtils.isEmpty(filterStr)) {
//            filterDateList = SourceDateList;
//        } else {
//            filterDateList.clear();
//            for (SortModel sortModel : SourceDateList) {
//                String name = sortModel.getName();
//                if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
//                    filterDateList.add(sortModel);
//                }
//            }
//        }
//
//        // 根据a-z进行排序
//        Collections.sort(filterDateList, pinyinComparator);
//        searchBrandAdapter.updateListView(filterDateList);
//    }

	public void getData_Search() {
		loadingToast.show();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
		params.put("UserInfoId", Utils.getUserId(getActivity()));
		params.put("Name", searchWord);
		GetDataQueue queue = new GetDataQueue();
		queue.setCallBack(callBack);
		queue.setActionName(GetDataConfing.GetAction_SelectsearchBrandList);
		queue.setWhat(GetDataConfing.what_SelectsearchBrandList);
		queue.setParamsNoJson(params);
		getDataUtil.getData(queue);

	}


	/**
	 * 获取服务器数据的返回信息
	 */
	private GetServicesDataUtil.IGetServicesDataCallBack callBack = new GetServicesDataUtil.IGetServicesDataCallBack() {

		@Override
		public void onLoaded(GetServicesDataQueue entity) {
			if (entity.isOk()) {

				if (ShowGetDataError.isOkAndCodeIsNot1(getActivity(), entity.getInfo())) {
					if (entity.what == GetDataConfing.what_SelectsearchBrandList) {
						List<JsonMap<String, Object>> data = JsonParseHelper.getJsonMap_List_JsonMap(
								entity.getInfo(), JsonKeys.Key_Info);
						dataSearch = data;
						SourceDateList = filledData(dataSearch);
						initViews();
					} else if (entity.getWhat() == GetDataConfing.WHAT_GET_FOCUS_ON) {
						JsonMap<String, Object> dataObject = JsonParseHelper.getJsonMap(entity.getInfo());
						try {
							if (dataObject.getStringNoNull("Msg").equals(getString(R.string.attention_success))) {
								tv_if_attentioned.setSelected(true);
								tv_if_attentioned.setText(R.string.attentioned);

								MyApplication.getInstance().addAttendBrands(vendorId);
							} else {
								tv_if_attentioned.setSelected(false);
								tv_if_attentioned.setText(R.string.attention);
								MyApplication.getInstance().removeAttendBrands(vendorId);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				}
			} else {
				ShowGetDataError.showNetError(getActivity());
			}
			loadingToast.dismiss();
		}
	};

	private String vendorId;
	private TextView tv_if_attentioned;
	private BrandSearchAdapter.ItemAttentionChange callback2 = new BrandSearchAdapter.ItemAttentionChange() {
		@Override
		public void onStatusChange(int position, TextView tv_if_attention) {
			tv_if_attentioned = tv_if_attention;
			vendorId = SourceDateList.get(position).getId();
			if (Utils.isHasLogin(getActivity())) {
				((MainActivity) getActivity()).getDate_GetFocusOn(callBack, vendorId, getActivity());
			} else {
				activity.gotoLogin();
			}
		}
	};


	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);

		try {
			searchBrandAdapter.setList(SourceDateList);
			searchBrandAdapter.notifyDataSetChanged();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
